const Application = require('../models/Application');
const Job = require('../models/job');
const Resume = require('../models/resume');
const { Op } = require('sequelize');
const { sendApplicationNotification } = require('../services/notification.service');

// 获取所有投递（管理员）
exports.getAllApplications = async (req, res) => {
  try {
    const { page = 1, limit = 10, status } = req.query;
    const offset = (page - 1) * limit;
    const whereClause = status ? { status } : {};

    const { count, rows: applications } = await Application.findAndCountAll({
      where: whereClause,
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['applicationDate', 'DESC']],
      include: ['job', 'resume']
    });

    return res.status(200).json({
      success: true,
      data: {
        applications,
        pagination: {
          total: count,
          page: parseInt(page),
          limit: parseInt(limit),
          pages: Math.ceil(count / limit)
        }
      }
    });
  } catch (error) {
    console.error('获取所有投递失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取所有投递失败',
      error: error.message
    });
  }
};

// 获取单个投递详情
exports.getApplicationById = async (req, res) => {
  try {
    const { id } = req.params;
    const application = await Application.findByPk(id, {
      include: ['job', 'resume']
    });

    if (!application) {
      return res.status(404).json({
        success: false,
        message: '投递记录不存在'
      });
    }

    return res.status(200).json({
      success: true,
      data: application
    });
  } catch (error) {
    console.error('获取投递详情失败:', error);
    return res.status(500).json({
      success: false,
      message: '获取投递详情失败',
      error: error.message
    });
  }
};

// 删除投递记录
exports.deleteApplication = async (req, res) => {
  try {
    const { id } = req.params;
    const application = await Application.findByPk(id);

    if (!application) {
      return res.status(404).json({
        success: false,
        message: '投递记录不存在'
      });
    }

    await application.destroy();
    return res.status(200).json({
      success: true,
      message: '投递记录删除成功'
    });
  } catch (error) {
    console.error('删除投递记录失败:', error);
    return res.status(500).json({
      success: false,
      message: '删除投递记录失败',
      error: error.message
    });
  }
};


// 求职者申请职位
exports.applyJob = async (req, res) => {
  try {
    const { jobId } = req.body;
    const userId = req.user.id;

    // 检查职位是否存在
    const job = await Job.findByPk(jobId);
    if (!job) {
      return res.status(404).json({
        success: false,
        message: '职位不存在'
      });
    }

    // 检查用户是否有简历
    const resume = await Resume.findOne({ where: { userId } });
    if (!resume) {
      return res.status(400).json({
        success: false,
        message: '请先创建简历再申请职位'
      });
    }

    // 检查是否已申请过该职位
    const existingApplication = await Application.findOne({
      where: { jobId, resumeId: resume.id }
    });
    if (existingApplication) {
      return res.status(400).json({
        success: false,
        message: '您已申请过该职位'
      });
    }

    // 创建职位申请
    const application = await Application.create({
      jobId,
      resumeId: resume.id,
      status: 'pending',
      applicationDate: new Date()
    });

    // 发送申请通知给企业
    await sendApplicationNotification({
      companyId: job.companyId,
      jobId,
      applicationId: application.id,
      applicantName: resume.fullName
    });

    res.status(201).json({
      success: true,
      message: '职位申请成功',
      data: application
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '职位申请失败',
      error: error.message
    });
  }
};

// 求职者获取自己的申请记录
exports.getMyApplications = async (req, res) => {
  try {
    const userId = req.user.id;
    const { status, page = 1, limit = 10 } = req.query;
    const offset = (page - 1) * limit;

    // 获取用户简历
    const resume = await Resume.findOne({ where: { userId } });
    if (!resume) {
      return res.status(200).json({
        success: true,
        data: {
          applications: [],
          pagination: { total: 0, page: 1, limit: 10, pages: 0 }
        }
      });
    }

    // 构建查询条件
    const whereClause = { resumeId: resume.id };
    if (status) whereClause.status = status;

    const { count, rows: applications } = await Application.findAndCountAll({
      where: whereClause,
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['applicationDate', 'DESC']],
      include: ['job']
    });

    res.status(200).json({
      success: true,
      data: {
        applications,
        pagination: {
          total: count,
          page: parseInt(page),
          limit: parseInt(limit),
          pages: Math.ceil(count / limit)
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取申请记录失败',
      error: error.message
    });
  }
};

// 企业获取职位的申请列表
exports.getJobApplications = async (req, res) => {
  try {
    const { jobId, status, page = 1, limit = 10 } = req.query;
    const companyId = req.user.id;
    const offset = (page - 1) * limit;

    // 验证职位是否属于当前企业
    const job = await Job.findOne({
      where: { id: jobId, companyId }
    });
    if (!job) {
      return res.status(404).json({
        success: false,
        message: '职位不存在或无权查看'
      });
    }

    // 构建查询条件
    const whereClause = { jobId };
    if (status) whereClause.status = status;

    const { count, rows: applications } = await Application.findAndCountAll({
      where: whereClause,
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['applicationDate', 'DESC']],
      include: ['resume']
    });

    res.status(200).json({
      success: true,
      data: {
        applications,
        pagination: {
          total: count,
          page: parseInt(page),
          limit: parseInt(limit),
          pages: Math.ceil(count / limit)
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取职位申请列表失败',
      error: error.message
    });
  }
};

// 企业更新申请状态
exports.updateApplicationStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status, feedback, interviewTime, interviewLocation } = req.body;
    const companyId = req.user.id;

    // 查询申请并验证所属职位
    const application = await Application.findByPk(id, {
      include: ['job']
    });

    if (!application) {
      return res.status(404).json({
        success: false,
        message: '申请记录不存在'
      });
    }

    // 验证职位是否属于当前企业
    if (application.job.companyId !== companyId) {
      return res.status(403).json({
        success: false,
        message: '无权操作此申请'
      });
    }

    // 更新申请状态
    await application.update({
      status,
      feedback,
      interviewTime: status === 'interview' ? interviewTime : null,
      interviewLocation: status === 'interview' ? interviewLocation : null
    });

    // 发送状态更新通知给求职者
    await sendApplicationNotification({
      userId: application.resume.userId,
      jobId: application.jobId,
      applicationId: application.id,
      status,
      feedback
    });

    res.status(200).json({
      success: true,
      message: '申请状态更新成功',
      data: application
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新申请状态失败',
      error: error.message
    });
  }
};

// 获取申请详情
exports.getApplicationDetails = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;
    const userRole = req.user.role;

    const application = await Application.findByPk(id, {
      include: ['job', 'resume']
    });

    if (!application) {
      return res.status(404).json({
        success: false,
        message: '申请记录不存在'
      });
    }

    // 权限验证：求职者只能查看自己的申请，企业只能查看自己职位的申请
    if (userRole === 'job_seeker' && application.resume.userId !== userId) {
      return res.status(403).json({
        success: false,
        message: '无权查看此申请'
      });
    }

    if (userRole === 'company') {
      const job = await Job.findByPk(application.jobId);
      if (job.companyId !== userId) {
        return res.status(403).json({
          success: false,
          message: '无权查看此申请'
        });
      }
    }

    res.status(200).json({
      success: true,
      data: application
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取申请详情失败',
      error: error.message
    });
  }
};